package com.fingard.dsp.bank.directbank.weixin01.domain.task;

import com.fingard.dsp.bank.directbank.weixin01.domain.DomainDetection;
import com.fingard.dsp.bank.directbank.weixin01.domain.common.DomainConstants;
import com.fingard.dsp.bank.directbank.weixin01.domain.common.DomainUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;


/**
 * 【定时探测主域名连通性策略】探测主域名连通性定时器
 * @author liujinhui
 */
public class DomainDetectionTimer extends TimerTask {

    private Logger logger = LoggerFactory.getLogger(DomainDetectionTimer.class);

    // 每次连续探测次数
    public static final int PROBE_NUM = 5;
    private Timer timer;
    private DomainDetection domainService;

    public DomainDetectionTimer(Timer timer, DomainDetection domainService) {
        this.timer = timer;
        this.domainService = domainService;
    }

    @Override
    public void run() {
        if (!domainService.getTimerStatus()) {
            // 关闭定时器
            logger.info("【定时探测主域名连通性策略】定时器关闭");
            this.timer.cancel();
        } else {
            // 微信支付域名请求上报数据统计
            int countMch = 0;
            String currentDomainMch = DomainConstants.API_MCH_WEIXIN_DOMAIN;
            // 探测主域名连通性
            for (int idx = 0; idx < PROBE_NUM; idx++) {
                boolean bo = DomainUtil.domainLinkTest(DomainConstants.API_MCH_WEIXIN_DOMAIN);
                if (bo) {
                    countMch++;
                }
            }
            // 根据探测结果分析主域名是否能正常提供服务并且计算出当前使用主域名还是备用域名
            if (countMch < 3) {
                currentDomainMch = DomainConstants.API_MCH_WEIXIN_RESERVE_DOMAIN;
            }
            logger.info("【定时探测主域名连通性策略】探测域名:"
                    + DomainConstants.API_MCH_WEIXIN_DOMAIN + ";成功连接次数:"
                    + countMch);
            // 更新当前域名
            domainService.setDomain(DomainConstants.DomainType.API_MCH, currentDomainMch);

            // 公共平台域名请求上报数据统计
            int count = 0;
            String currentDomain = DomainConstants.API_WEIXIN_DOMAIN;
            // 探测主域名连通性
            for (int idx = 0; idx < PROBE_NUM; idx++) {
                boolean bo = DomainUtil.domainLinkTest(DomainConstants.API_WEIXIN_DOMAIN);
                if (bo) {
                    count++;
                }
            }
            // 根据探测结果分析主域名是否能正常提供服务并且计算出当前使用主域名还是备用域名
            if (count < 3) {
                currentDomain = DomainConstants.API_WEIXIN_RESERVE_DOMAIN;
            }
            logger.info("【定时探测主域名连通性策略】探测域名:"
                    + DomainConstants.API_WEIXIN_DOMAIN + ";成功连接次数:" + count);
            // 更新当前域名
            domainService.setDomain(DomainConstants.DomainType.API, currentDomain);
        }
    }
}
